package com.example.goodsmanagementcabinet.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.AppUtils;
import com.example.goodsmanagementcabinet.R;
import com.example.goodsmanagementcabinet.base.BaseActivity;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;
import com.example.goodsmanagementcabinet.base.MyDialog;
import com.example.goodsmanagementcabinet.bean.UserBean;
import com.example.goodsmanagementcabinet.db.DatabaseManager;
import com.example.goodsmanagementcabinet.finger.FingerHandler;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.serialport.SerialPortConnect;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static java.lang.Thread.sleep;

@Fullscreen
@EActivity(R.layout.activity_main)
public class HomeActivity extends BaseActivity implements View.OnClickListener, Handler.Callback {

    private static final int HANDLER_CONNECT_SERPORT = 1;
    @ViewById
    EditText userEd, passwordEd;
    @ViewById
    LinearLayout btnLogin;
    private Handler mHandler;
    private boolean sereialpoerIsOPen;
    String fingerTemple = "";
    UserBean myuser;

    @AfterViews
    public void afterViews() {
        mHandler = new Handler(this);
        btnLogin.setOnClickListener(this);
        mHandler.sendEmptyMessageDelayed(HANDLER_CONNECT_SERPORT, 2000);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                if (TextUtils.equals(userEd.getText().toString().trim(), "admin") && TextUtils.equals(passwordEd.getText().toString().trim(), "1")) {
                    speak("登陆成功");
                    userEd.setText("");
                    passwordEd.setText("");
                    UserBean user = new UserBean();
                    user.setNickname("admin");
                    user.setPassWord("1");
                    user.setUserId("admin");
                    Intent intent = new Intent(HomeActivity.this, AdminManagerView_.class);
                    intent.putExtra("User", user);
                    startActivity(intent);
                } else {
                    if (TextUtils.isEmpty(userEd.getText().toString().trim())) {
                        speak("请输入用户名");
                    } else {
                        UserBean myuser = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUserByusrName(userEd.getText().toString().trim());
                        if (myuser != null) {
                            if (TextUtils.isEmpty(passwordEd.getText().toString().trim())) {
                                myuser = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUserByusrName(userEd.getText().toString().trim());
                                fingerTemple = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryFingerByUserId(myuser.getUserId());
                                if (!TextUtils.isEmpty(fingerTemple)) {
                                    macthFinger(fingerTemple);
                                } else {
                                    speak("未查询到指纹信息");
                                }
                            } else {
                                if (TextUtils.equals(myuser.getPassWord(), passwordEd.getText().toString().trim())) {
                                    speak("登陆成功");
                                    userEd.setText("");
                                    passwordEd.setText("");
                                    Intent intent = new Intent(HomeActivity.this, AdminManagerView_.class);
                                    intent.putExtra("User", myuser);
                                    startActivity(intent);
                                } else {
                                    speak("用户名密码错误");
                                }
                            }
                        } else {
                            speak("用户名密码错误");
                        }
                    }
                }
                break;
        }
    }

    @Background
    public void macthFinger(String finger) {
        if (!TextUtils.isEmpty(finger)) {
            FingerHandler.getInstance().match(finger);
        }
    }

    public void SerialPortConnect() {
        sereialpoerIsOPen = SerialPortConnect.getInstance().connect("/dev/ttyS3", 9600);
        if (!sereialpoerIsOPen) {
            speak("串口打开失败");
        }
    }

    @UiThread
    public void upDateUI() {
        speak(myuser.getNickname() + "验证通过");
        userEd.setText("");
        passwordEd.setText("");
        Intent intent = new Intent(HomeActivity.this, AdminManagerView_.class);
        intent.putExtra("User", myuser);
        startActivity(intent);
    }

    @Subscribe
    @Background
    public void handlerOtto(OttoMsg msg) {
        if (TextUtils.equals(OttoMsg.OTTO_MACTH_FINGER_SUCESS, msg.which)) {
            upDateUI();
        } else if (TextUtils.equals(OttoMsg.OTTO_MACTH_FINGER_FAILE, msg.which)) {
            macthFinger(fingerTemple);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(HANDLER_CONNECT_SERPORT);
        FingerHandler.getInstance().close();
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case HANDLER_CONNECT_SERPORT:
                mHandler.removeMessages(HANDLER_CONNECT_SERPORT);
                SerialPortConnect();
                break;
        }
        return true;
    }
}